<template>
  <div>
    <UserHeader @addList="addList"></UserHeader>
    <TodoList :doingList="doingList" :doneList="doneList"></TodoList>
    <UserFooter @clearAll="clearAll"></UserFooter>
  </div>
</template>

<script>
import UserHeader from "./components/UserHeader.vue";
import TodoList from "./components/TodoList.vue";
import UserFooter from "./components/UserFooter.vue";

export default {
  name: "App",
  components: { UserHeader, TodoList, UserFooter },
  data() {
    return {
      todoList: [],
    };
  },
  computed: {
    //通过过滤todoList数据，得到未做好的列表和已做好的列表
    doingList() {
      return this.todoList.filter(function (item, index) {
        return !item.isDone;
      });
    },
    doneList() {
      return this.todoList.filter(function (item, index) {
        return item.isDone;
      });
    },
  },
  methods: {
    //将数据添加至todoList
    addList(val) {
      this.todoList.unshift({
        content: val,
        isDone: false,
        id: Date.now(),
      });
      //保存数据
      this.saveData();
    },
    //将数据保存到本地存储
    saveData() {
      localStorage.todoList = JSON.stringify(this.todoList);
    },
    // 勾选
    checkDone(id) {
      this.todoList.forEach((todo) => {
        if (todo.id === id) {
          todo.isDone = !todo.isDone;
        }
      });
      //每次修改都必须保存
      this.saveData();
    },
    // 修改数据
    updateTodo(id, val) {
      this.todoList.forEach((todo) => {
        if (todo.id === id) {
          todo.content = val;
        }
      });
      //每次修改都必须保存
      this.saveData();
    },
    //删除数据
    deleteItem(id) {
      this.todoList = this.todoList.filter((todo) => {
        return todo.id !== id;
      });
      this.saveData();
    },
    // 删除所有已完成事例
    delDone() {
      this.todoList = this.todoList.filter((todo) => {
        return todo.isDone === false;
      });
      this.saveData();
    },
    //清除所有数据
    clearAll() {
      localStorage.clear();
      this.todoList = [];
    },
  },
  mounted() {
    this.todoList = localStorage.todoList
      ? JSON.parse(localStorage.todoList)
      : [];

    this.$bus.$on("checkDone", this.checkDone);
    this.$bus.$on("deleteItem", this.deleteItem);
    this.$bus.$on("updateTodo", this.updateTodo);
    this.$bus.$on("delDone", this.delDone);
    this.$bus.$on("clearAll", this.clearAll);
  },
  beforeDestroy() {
    this.$bus.$off("checkDone");
    this.$bus.$off("deleteItem");
    this.$bus.$off("updateTodo");
    this.$bus.$off("delDone");
    this.$bus.$off("clearAll");
  },
};
</script>

<style>
@import url("./assets/reset.css");
body {
  background-color: #cdcdcd;
}
</style>